#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/3/24 17:56
# @Author  : LiShan
# @Email   : lishan_1997@126.com
# @File    : external.py
# @Note    : this is note
"""
    使用示例：
    program_class = "WindowsForms10.Window.8.app.0.378734a"
    program_title = "VISSIM 4.30-01 - (Untitled)"
    para = [program_path, program_class, program_title]
    program_window = external.display_external_program(para)
    self.horizontalLayout_sim.addWidget(program_window)
"""
import os
import time
import threading
import win32gui
from PyQt5.QtGui import QWindow
from PyQt5.QtWidgets import QMainWindow, QWidget


class display_external_program(QMainWindow):

    def __init__(self, para):
        super().__init__()
        self.program_path = para[0]
        self.program_class = para[1]
        self.program_title = para[2]
        self.get_window()

    def get_window(self):
        task = threading.Thread(target=os.startfile, args=(self.program_path, ))
        task.start()
        start = time.time()
        while True:
            hwnd = win32gui.FindWindowEx(0, 0, self.program_class, self.program_title)
            wait_time = time.time() - start
            if hwnd != 0:
                external_window = QWindow.fromWinId(hwnd)
                external_window = QWidget.createWindowContainer(external_window, self)
                self.setCentralWidget(external_window)
                break
            elif wait_time > 10:
                return
